package com.lanou.authcenter.service.impl;

import com.lanou.authcenter.service.IUserService;
import com.lanou.k12.entity.ResultObject;
import com.lanou.k12.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
public class UserService implements IUserService {


    @Override
    public ResultObject login(User u) {
        ResultObject obj = new ResultObject();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken upt = new UsernamePasswordToken(u.getUsername(), u.getPwd());
        if (subject.isAuthenticated()) {
            obj.setStatus(0);
            obj.setInfo("请勿重复登录");
           return obj;
        }
        try {
            subject.login(upt);
            obj.setStatus(1);
            obj.setInfo("登陆成功");
            User user = (User) subject.getPrincipal();
            user.setPwd(null);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            obj.setStatus(0);
            obj.setInfo("登陆失败");
        }
        return obj;
    }

    @Override
    public ResultObject logout() {
        ResultObject obj = new ResultObject();
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
            obj.setStatus(1);
        } else {
            obj.setStatus(0);
            obj.setInfo("要不先登个录？");
        }
        return obj;
    }
}
